package shopping

import (
	"time"
	"strconv"
	"wxsdk/miniapp/shop"
	"dhfshop/utils/math"
	"dhfshop/models/org"
	"dhfshop/models/isv"
	"dhfshop/models/member"
	"dhfshop/models/sale"
	"dhfshop/models/shopping"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

// 购物车管理
type CartController struct {
	base.BaseController
}

func (this *CartController) List() {
    curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
		this.ServeError("user is not login")
	    return
	}
	shopId, _ := this.GetInt("shop_id")
	cart, err := shopping.GetCarts(curUserId, int64(shopId))
	if err != nil {
	    this.ServeError(err.Error())
	    return
	} 
	this.Data["json"] = cart
	this.ServeJSON()
}

func (this *CartController) Post() {
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
		this.ServeError("user is not login")
	    return
	}
	var v shopping.CartItem
	this.ParseForm(&v)
	valid := validation.Validation{}
	//valid.Required(v.BuyerId, "buyer_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	v.BuyerId = int64(curUserId)
	if len(v.ItemIdStr) > 0 {
	    v.ItemId, _= strconv.ParseInt(v.ItemIdStr, 10, 64)
	}
	if len(v.SkuIdStr) > 0 {
	    v.SkuId, _= strconv.ParseInt(v.SkuIdStr, 10, 64)
	}
	item, err := sale.GetItemByItemId(v.ItemId)
	if err != nil {
		this.ServeError(err.Error())
		return   
	}	
	store, err := org.GetStoreByPartnerId(item.PartnerId)
	if err != nil {
        this.ServeError(err.Error())
		return  
    }
	v.ShopId = store.StoreId
	if _, err := shopping.AddCart(&v); err != nil {
	    this.ServeError(err.Error())
		return
	}
	curAppId := this.Ctx.Input.GetData("curAppId").(string)
	if len(curAppId) == 0 {
		beego.Debug("curAppId is invalid")
	}
	custAccount, err := isv.GetCustAccountByAppId(curAppId)
	if err != nil {
		beego.Debug("GetCustAccountByAppId:", err.Error())
	}
	memberValue, err := member.GetMemberById(curUserId)
	if err != nil {
	    beego.Debug("GetMemberById:", err.Error())
	}
	categoryId := strconv.FormatInt(item.CategoryId, 10)
	price := int(math.MultiTotalPriceInt(item.Price, 100))
	if custAccount != nil && memberValue != nil {
	    if err = shop.AddShoppingList(custAccount.AccessToken,memberValue.OpenID,v.ItemIdStr,v.SkuIdStr,categoryId,item.Image,item.Title,price); err != nil {
			beego.Debug("AddShoppingList:", err.Error())
		}
	}
	rsp := struct {
		CartItemId    int64      `json:"cart_item_id"`
	    Created   time.Time    `json:"created"`
	}{CartItemId: v.CartItemId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *CartController) Put() {
	var v shopping.CartItem
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.CartItemId, "cart_item_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	if len(v.ItemIdStr) > 0 {
	    v.ItemId, _= strconv.ParseInt(v.ItemIdStr, 10, 64)
	}
	if len(v.SkuIdStr) > 0 {
	    v.SkuId, _= strconv.ParseInt(v.SkuIdStr, 10, 64)
	}
    if err := shopping.UpdateCart(&v, "quantity"); err != nil{
		this.ServeError(err.Error())
		return
	}
	rsp := struct {
		    CartItemId int64         `json:"cart_item_id"`
	        Modified   time.Time   `json:"modified"`
	    }{CartItemId:v.CartItemId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}


func (this *CartController) Delete() {
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
		beego.Debug("user is not login")
	}
	curAppId := this.Ctx.Input.GetData("curAppId").(string)
	if len(curAppId) == 0 {
		beego.Debug("curAppId is invalid")
	}
	custAccount, err := isv.GetCustAccountByAppId(curAppId)
	if err != nil {
	    beego.Debug("GetCustAccountByAppId:", err.Error())
	}
	cartItemId, err := this.GetInt("cart_item_id")
	if err != nil {
		this.ServeError("cart_item_id is null")
		return 
	}
	if err := shopping.RemoveCart(cartItemId); err != nil{
		this.ServeError(err.Error())
		return
	}
	memberValue, err := member.GetMemberById(curUserId)
	if err != nil {
	    beego.Debug("GetMemberById:", err.Error())
	}
	cartItem, err := shopping.GetCartItemById(int64(cartItemId))
	if err != nil {
	    beego.Debug("GetCartItemById:", err.Error())
	}
	if custAccount != nil && memberValue != nil && cartItem != nil {
	    if err = shop.DelShoppingList(custAccount.AccessToken,memberValue.OpenID,cartItem.ItemIdStr,cartItem.SkuIdStr); err != nil {
			beego.Debug("DelShoppingList:", err.Error())
		}
	}
	rsp := struct {
		    CartItemId  int       `json:"cart_item_id"`
	        Modified  time.Time   `json:"modified"`
	    }{CartItemId:cartItemId, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
